package com.reny.ll.git.mvvm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.reny.ll.git.mvvm.extras.postNext
import com.reny.ll.git.mvvm.state.LoadState
import com.reny.ll.git.mvvm.state.RefreshState
import com.reny.ll.git.mvvm.state.STATE_CONTENT
import com.reny.ll.git.mvvm.state.STATE_LOADING

abstract class BaseViewModel : ViewModel() {

    //如果是第一次进入页面
    open var isFirst:Boolean = true

    open var enableLoadMore:Boolean = true

    val loadState: MutableLiveData<Int> = MutableLiveData(-1)
    val refreshState: MutableLiveData<RefreshState> = MutableLiveData(RefreshState())

    var isRefresh = true


    open fun loadData(refresh: Boolean) {
        if(isFirst){
            //如果是第一次进入页面 可以展示LOADING页面
            if(loadState.value != STATE_LOADING) {
                loadState.postValue(STATE_LOADING)
            }
        }
    }

    //数据加载完成后应该调用的方法 设置相关UI状态
    open fun setLoadState(@LoadState state: Int, noMore:Boolean, isRefresh:Boolean, resetFirst:Boolean = false){
        this.isRefresh = isRefresh

        if(resetFirst && isRefresh){
            isFirst = true
        }

        if(isFirst || resetFirst){
            if(loadState.value != state) {
                loadState.postValue(state)
            }
        }

        if(isFirst && state == STATE_CONTENT){
            isFirst = false
        }

        refreshState.postNext {
            it.copy(noMore = noMore)
        }
    }

}